<template>
  <div class="config-page">
    <t-card title="平台账号配置" class="config-card">
      <t-table
        ref="tableRef"
        row-key="key"
        :columns="columns"
        :data="tableData"
        :hover="hover"
        :stripe="stripe"
        :editable-row-keys="editableRowKeys"
        table-layout="fixed"
        bordered
        :loading="loading"
        :row-height="80"
        @row-edit="onRowEdit"
        @row-validate="onRowValidate"
        @validate="onValidate"
      >
        <!-- Cookies信息列 -->
        <template #cookiesInfo="{ row }">
          <div class="cookies-cell">
            <div v-if="isEditing(row.key)">
              <t-input
                v-model="editMap[row.key]?.editedRow.cookiesInfo"
                type="password"
                :maxlength="8000"
                :autoWidth="false"
                clearable
              />
            </div>
            <div v-else class="cookies-content">
              <span class="cookies-text">
                {{ getMaskedCookies(row.cookiesInfo) }}
              </span>
              <t-popup
                placement="top"
                :content="row.cookiesInfo"
                :show-arrow="true"
                trigger="click"
              >
                <t-button variant="text" size="small">
                  查看
                </t-button>
              </t-popup>
            </div>
          </div>
        </template>

        <!-- 操作栏 -->
        <template #operate="{ row }">
          <div class="table-operations">
            <t-space>
              <t-button
                v-if="!isEditing(row.key)"
                variant="text"
                theme="primary"
                :disabled="row.status === -1"
                @click="onEdit($event)"
                :data-id="row.key"
              >
                编辑
              </t-button>
              <template v-else>
                <t-button
                  variant="text"
                  theme="primary"
                  @click="onSave($event)"
                  :data-id="row.key"
                >
                  保存
                </t-button>
                <t-button
                  variant="text"
                  theme="danger"
                  @click="onCancel($event)"
                  :data-id="row.key"
                >
                  取消
                </t-button>
              </template>
            </t-space>
          </div>
        </template>

        <!-- 状态列 -->
        <template #status="{ row }">
          <t-tag :theme="getStatusTheme(row.status)" variant="light-outline">
            {{ getStatusText(row.status) }}
          </t-tag>
        </template>
      </t-table>
    </t-card>
  </div>
</template>

<script lang="ts">
import Vue from 'vue';
import { Input, MessagePlugin, Table, Button, Space, Card, Tag, Popup } from 'tdesign-vue';

// 定义平台名称映射
const PLATFORM_MAP: Record<string, string> = {
  xhs: '小红书',
  dy: '抖音',
  ks: '快手',
  wb: '微博',
  bili: 'B站',
  tieba: '贴吧',
  zhihu: '知乎',
};

// 定义状态样式映射
const STATUS_STYLE_MAP: Record<number, { text: string; color: string }> = {
  0: { text: '生效中', color: '#0052D9' },
  [-1]: { text: '已失效', color: '#FFAA00' },
  [-2]: { text: '未创建', color: '#999999' },
};

// 定义接口
interface TableRow {
  key: string;
  platformName: string;
  accountName: string;
  cookiesInfo: string;
  status: number;
  showCookies?: boolean;
}

export default Vue.extend({
  name: 'Config',

  components: {
    't-table': Table,
    't-button': Button,
    't-space': Space,
    't-card': Card,
    't-tag': Tag,
    't-input': Input,
    't-popup': Popup,
  },

  data() {
    return {
      loading: false,
      hover: true,
      stripe: false,
      editableRowKeys: [] as string[],
      tableData: [] as TableRow[],
      platformOptions: ['小红书', '抖音', '快手', '微博', 'B站', '贴吧', '知乎'],
      editMap: {} as Record<string, { rowIndex: number; editedRow: TableRow }>,
      columns: [
        {
          title: '平台名称',
          colKey: 'platformName',
          width: 120,
          align: 'left',
          editable: false,
        },
        {
          title: '账户名称',
          colKey: 'accountName',
          width: 180,
          align: 'left',
          edit: {
            component: Input,
            props: {
              clearable: true,
              autoWidth: true,
            },
            rules: [
              { required: true, message: '账户名称不能为空' },
              { max: 20, message: '字符数量不能超过 20' },
            ],
            showEditIcon: false,
          },
        },
        {
          title: 'Cookies信息',
          colKey: 'cookiesInfo',
          width: 400,
          cell: 'cookiesInfo',
          align: 'left',
        },
        {
          title: '状态',
          colKey: 'status',
          width: 120,
          align: 'center',
          cell: 'status',
        },
        {
          title: '操作',
          colKey: 'operate',
          width: 120,
          align: 'center',
          fixed: 'right',
        },
      ],
    };
  },

  created() {
    // 初始化表格数据，每个平台一行，账户名称和Cookies信息默认为空
    this.tableData = this.platformOptions.map((platform) => ({
      key: `new-${platform}`, // 使用 'new-' 前缀确保唯一性
      platformName: platform,
      accountName: '',
      cookiesInfo: '',
      status: -2, // 未创建状态
    }));
    this.fetchUserConfigs();
  },

  methods: {
    /**
     * 将平台英文名称转换为中文显示
     * @param row 当前行数据
     * @returns 平台中文名称
     */
    getPlatformDisplayName(row?: TableRow): string {
      if (row && row.platformName) {
        return PLATFORM_MAP[row.platformName] || row.platformName;
      }
      return '';
    },

    /**
     * 获取状态对应的文本
     * @param status 状态码
     * @returns 状态文本
     */
    getStatusText(status: number): string {
      return STATUS_STYLE_MAP[status]?.text || '未知状态';
    },

    /**
     * 获取状态对应的颜色
     * @param status 状态码
     * @returns 状态颜色
     */
    getStatusColor(status: number): string {
      return STATUS_STYLE_MAP[status]?.color || '#000000';
    },

    /**
     * 检查行是否处于编辑状态
     * @param key 行键
     * @returns 是否正在编辑
     */
    isEditing(key: string): boolean {
      return this.editableRowKeys.includes(key);
    },

    /**
     * 编辑操作
     * @param event 点击事件
     */
    onEdit(event: Event): void {
      const target = event.currentTarget as HTMLElement;
      const id = target.getAttribute('data-id');
      if (id && !this.editableRowKeys.includes(id)) {
        this.editableRowKeys.push(id);
        const rowIndex = this.tableData.findIndex((row) => row.key === id);
        if (rowIndex !== -1) {
          // 将当前行数据存储到 editMap 中
          this.editMap[id] = {
            rowIndex,
            editedRow: { ...this.tableData[rowIndex] },
          };
        }
      }
    },
    /**
     * 取消编辑操作
     * @param event 点击事件
     */
    onCancel(event: Event): void {
      const target = event.currentTarget as HTMLElement;
      const id = target.getAttribute('data-id');
      if (id) {
        const index = this.editableRowKeys.indexOf(id);
        if (index !== -1) {
          this.editableRowKeys.splice(index, 1);
        }
      }
    },

    /**
     * 保存操作
     * @param event 点击事件
     */
    async onSave(event: Event): Promise<void> {
      const target = event.currentTarget as HTMLElement;
      const id = target.getAttribute('data-id');
      if (!id) return;

      try {
        const validation = await this.$refs.tableRef.validateRowData(id);
        if (validation?.result?.length) {
          const error = validation.result[0];
          MessagePlugin.error(`${error.col.title} ${error.errorList[0].message}`);
          return;
        }

        // 从 editMap 中获取最新的编辑数据
        const current = this.editMap[id];
        if (!current) {
          MessagePlugin.error('未找到要保存的数据');
          return;
        }

        const rowData = current.editedRow;
        const isExisting = !id.startsWith('new-'); // 判断是否为已存在的账户
        const platformKey = Object.keys(PLATFORM_MAP).find(key => PLATFORM_MAP[key] === rowData.platformName);
        let response;
        if (isExisting) {
          // 已存在账户，使用 PUT 请求更新
          response = await this.$request.put(`/system/crawler-cookies-accounts/${rowData.key}/`, {
            account_name: rowData.accountName,
            cookies: rowData.cookiesInfo,
          });
        } else {
          // 新创建账户，使用 POST 请求创建
          response = await this.$request.post('/system/crawler-cookies-accounts/', {
            account_name: rowData.accountName,
            platform_name: platformKey,
            cookies: rowData.cookiesInfo,
          });
        }
        console.log(response)
        if (response?.code === 0 || response?.status === 200) {
          MessagePlugin.success('保存成功');
          this.updateEditState(id);

          if (!isExisting && response.id) {
            // 更新表格中的 key 为后端返回的 ID
            rowData.key = String(response.id);
            rowData.status = 0; // 设置为生效中
          }

          // 更新 tableData 中的数据
          this.tableData.splice(current.rowIndex, 1, rowData);

          // 刷新数据
          await this.fetchUserConfigs();
        } else {
          MessagePlugin.error(response?.message || '保存失败');
        }
      } catch (error) {
        console.error('保存失败:', error);
        MessagePlugin.error('保存过程中出现错误');
      }
    },

    /**
     * 更新编辑状态，移除可编辑行
     * @param id 行键
     */
    updateEditState(id: string): void {
      const index = this.editableRowKeys.findIndex((key) => key === id);
      if (index !== -1) {
        this.editableRowKeys.splice(index, 1);
      }
      // 移除 editMap 中的记录
      delete this.editMap[id];
    },

    /**
     * 行校验反馈事件
     * @param params 校验参数
     */
    onRowValidate(params: any): void {
      console.log('行校验结果:', params);
    },

    /**
     * 表格校验反馈事件
     * @param params 校验参数
     */
    onValidate(params: any): void {
      console.log('表格校验结果:', params);
    },

    /**
     * 行编辑事件
     * @param params 编辑参数
     */
    onRowEdit(params: any): void {
      const { row, col, value } = params;
      const oldRowData = this.editMap[row.key]?.editedRow || row;
      const editedRow = {
        ...oldRowData,
        [col.colKey]: value,
      };
      this.editMap[row.key] = {
        ...params,
        editedRow,
      };
    },

    /**
     * 请求后端获取当前登录用户的配置并填充到表格
     */
    async fetchUserConfigs(): Promise<void> {
      this.loading = true;
      try {
        const response = await this.$request.get('/system/crawler-cookies-accounts/');
        if (response.status === 200 && response.data) {
          const existingAccounts: any[] = response.data;
          // 更新表格数据，将后端返回的账户信息填充到对应的平台行
          this.tableData = this.tableData.map((row) => {
            const platformKey = Object.keys(PLATFORM_MAP).find(key => PLATFORM_MAP[key] === row.platformName);
            const account = existingAccounts.find((acc) => acc.platform_name === platformKey);
            if (account) {
              return {
                ...row,
                key: String(account.id),
                accountName: account.account_name,
                cookiesInfo: account.cookies,
                status: account.status,
                showCookies: false,
              };
            }
            return {
              ...row,
              showCookies: false,
            };
          });
        } else {
          MessagePlugin.error(response?.message || '加载配置信息失败');
        }
      } catch (error) {
        MessagePlugin.error('请求配置信息出错');
        console.error('请求配置信息出错:', error);
      } finally {
        this.loading = false;
      }
    },

    // 获取状态对应的主题色
    getStatusTheme(status: number): string {
      const themeMap = {
        0: 'success',
        [-1]: 'warning',
        [-2]: 'default',
      };
      return themeMap[status] || 'default';
    },

    // 处理Cookies信息显示
    getMaskedCookies(cookies: string): string {
      if (!cookies) return '暂无信息';
      return '*'.repeat(20); // 统一显示固定长度的掩码
    },

    // 切换Cookies显示状态
    toggleCookiesView(row: TableRow): void {
      this.$set(row, 'showCookies', !row.showCookies);
    },
  },
});
</script>

<style lang="less" scoped>
.config-page {
  padding: 20px;

  .config-card {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.05);
  }

  .cookies-cell {
    .cookies-content {
      display: flex;
      align-items: center;
      justify-content: space-between;
      
      .cookies-text {
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        margin-right: 8px;
        word-break: break-all;
      }
    }
  }

  .table-operations {
    .t-button {
      padding: 0 4px;
      
      &:hover {
        background-color: rgba(0, 0, 0, 0.04);
      }
    }
  }

  // 添加弹出层样式
  :deep(.t-popup) {
    max-width: 500px;
    word-break: break-all;
    white-space: pre-wrap;
  }
}
</style>
